(function ($) {
  var ERROR_CODE = {
    '100': 'authorized', // 权限有效
    '101': 'unauthorized', // 权限无效
    '102': 'auth-timeout', // 鉴权请求网络超时
    '103': 'no-network', // 无网络
    '400': 'bad-request', // ajax请求失败
    '401': 'params-error', // 请求参数异常
    '500': 'server-error', // 服务器错误
    '502': 'transfer-error', // 转换失败
    '504': 'server-timeout', // 转换超时
    '510': 'download-failed', // 文件原始地址下载失败
    '511': 'file-size-out-of-limit' // 文件大小超出限制
  }

  var queryString = function (name) {
    var query = window.location.search
    var map = {}
    if (query.indexOf('?') >= 0) {
      var params = query.substr(1).split('&')
      for (var i = params.length - 1; i >= 0; i--) {
        var keyValue = params[i]
        var index = keyValue.indexOf('=')
        if (index > 0 && index < keyValue.length) {
          map[keyValue.substr(0, index).toLowerCase()] = unescape(keyValue.substr(index + 1))
        }
      }
    }
    queryString = function (name) {
      var val = map[name.toLowerCase()]
      return typeof val !== 'undefined' ? val : null
    }
    return queryString(name)
  }

  var baseUrl
  var convertParams
  var errorShown = null
  var eventId = queryString('eventId')
  var debug = queryString('debug') === '1'
  var isIOS = queryString('platform') === '2'
  var i18n = $.i18n()
  i18n.locale = queryString('lang') === '1033' ? 'en' : 'zh-cn'
  i18n.load({
    en: {
      close: 'Close',
      retry: 'Retry',
      notice: 'Internal documents, prohibit the dissemination of zte.com.cn',
      unauthorized: 'Unauthorized document',
      'auth-timeout': 'Authentication request network timeout',
      'no-network': 'No network',
      'server-timeout': 'Server timeout',
      'bad-request': 'Request failed',
      'server-error': 'Cannot preview specified file',
      'file-size-out-of-limit': 'File size exceeded limit',
      'excel-over-500-rows': 'Docview shows up to 500 rows at most. Please download the full file.'
    },
    'zh-cn': {
      close: '关闭',
      retry: '重试',
      notice: '内部文件，禁止传播 zte.com.cn',
      unauthorized: '文档未授权',
      'auth-timeout': '鉴权请求网络超时',
      'no-network': '无网络',
      'server-timeout': '转换超时',
      'bad-request': '请求失败',
      'server-error': '无法预览指定的文件',
      'file-size-out-of-limit': '文件大小超出限制',
      'excel-over-500-rows': '在线浏览最多显示500行内容，完整内容请下载查看'
    }
  })

  $.extend({
    viewSetting: {
      eventId: eventId,
      isIOS: isIOS,
      lang: i18n.locale
    },
    initDocView: function (docViewUrl, sysCode, viewInfo) {
      baseUrl = docViewUrl
      convertParams = {
        sysCode: sysCode,
        docInfo: viewInfo,
        eventId: eventId
      }
    },
    getImgBase64: function (img) {
      var canvas = document.createElement('canvas')
      canvas.width = img.naturalWidth
      canvas.height = img.naturalHeight
      var ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.naturalWidth, img.naturalHeight)
      return canvas.toDataURL('image/png')
    },
    logger: {
      debug: function loggerDebug (message) { log('DEBUG', loggerDebug.caller.name, message) },
      info: function loggerInfo (message) { log('INFO', loggerInfo.caller.name, message) },
      warn: function loggerWarn (message) { log('WARN', loggerWarn.caller.name, message) },
      error: function loggerError (message) { log('ERROR', loggerError.caller.name, message) }
    },
    remoteLoad: function (params, done, fail) {
      $.ajax({
        type: 'GET',
        url: baseUrl + '/api/viewPage',
        data: $.extend(convertParams, params),
        dataType: 'json',
        crossDomain: true,
        timeout: 60000
      }).done(done).fail(fail)
    },
    throwError: function (code, retryCallback) {
      $.logger.error('错误代码:' + code + '-' + ERROR_CODE[code])
      if (code === '511') {
        // 文件大小超出直接退出
        retryCallback = null
      }
      if (code === '401') {
        // 参数异常直接退出
        code = '400'
        retryCallback = null
      }
      if (code === '502' || code === '510') {
        code = '500'
      }
      var msg = ERROR_CODE[code]
      if (typeof retryCallback === 'function') {
        if (!!errorShown && errorShown < '200') {
          // 正在呈现鉴权类异常，其他异常自动重试
          setTimeout(retryCallback, 1000)
          return
        }
        errorShown = code
        $('#view-loading-img').hide()
        $('#view-loading-retry .loading-retry-text').text($.i18n(msg))
        $('#view-loading-retry').show().one('click', function () {
          $.logger.debug('用户发起重试')
          errorShown = null
          $('#view-loading-retry').hide()
          $('#view-loading-img').show()
          setTimeout(retryCallback, 200)
        })
      } else {
        $('#view-loading-img').hide()
        $('#view-loading-retry .loading-retry-text').text($.i18n(msg))
        $('#view-loading-retry .loading-retry-button').text($.i18n('close'))
        $('#view-loading-retry').show().one('click', $.SDK.exitView)
      }
    },
    SDK: {
      jsComplete: function () {
        $.logger.debug('SDK.jsComplete()')
        if (isIOS) {
          if (window.webkit) window.webkit.messageHandlers.jsComplete.postMessage(null)
        } else if (window.ZteDocView) window.ZteDocView.jsComplete()
      },
      cacheImg: function (totalPages, page, data) {
        data = data.substr(22)
        var len = data.length
        var chunkSize = 102400.0
        var chunks = Math.ceil(len / chunkSize)
        for (var chunk = 0; chunk < chunks; chunk++) {
          var chunkData = data.substring(chunk * chunkSize, Math.min((chunk + 1) * chunkSize, len))
          $.logger.debug('SDK.cacheImg(' + totalPages + ',' + page + ',' + len + ',' + chunks + ',' + chunk + ',' + (chunkData.length >= 36 ? (chunkData.substr(0, 16) + '...' + chunkData.substr(chunkData.length - 16)) : chunkData) + '[' + chunkData.length + '])')
          if (isIOS) {
            if (window.webkit) {
              window.webkit.messageHandlers.cacheImg.postMessage({
                totalPages: totalPages,
                page: page,
                len: len,
                chunks: chunks,
                chunk: chunk,
                chunkData: chunkData
              })
            }
          } else if (window.ZteDocView) window.ZteDocView.cacheImg(totalPages, page, len, chunks, chunk, chunkData)
        }
      },
      authRetry: function () {
        $.logger.debug('SDK.authRetry()')
        if (isIOS) {
          if (window.webkit) window.webkit.messageHandlers.authRetry.postMessage(null)
        } else if (window.ZteDocView) window.ZteDocView.authRetry()
      },
      exitView: function () {
        $.logger.debug('SDK.exitView()')
        if (isIOS) {
          if (window.webkit) window.webkit.messageHandlers.exitView.postMessage(null)
        } else if (window.ZteDocView) window.ZteDocView.exitView()
      }
    }
  })

  var consoleArea
  $(function () {
    consoleArea = $('#webConsole textarea')
    $.logger.info('eventId: ' + eventId)
    $.logger.info('debug: ' + debug)
    $.logger.info('isIOS: ' + isIOS)
    $.logger.info('lang: ' + i18n.locale)

    if (debug) {
      var clickCount = 0
      var clickTime = new Date()
      var win = $(window)
      win.on('click', function () {
        if (new Date() - clickTime > 500) {
          clickCount = 0
        }
        clickTime = new Date()
        clickCount++
        if (clickCount >= 10) {
          showWebConsole()
        }
      })

      window.showLog = function () {
        if (isIOS) {
          showWebConsole()
        }
        return '1'
      }
    }

    function showWebConsole () {
      $('#viewMain').css('top', win.height() * 0.5)
      $('#webConsole').css('height', win.height() * 0.5).show()
      consoleArea.dblclick(function () {
        this.setSelectionRange(0, this.value.length)
        document.execCommand('Copy')
      })
    }
  })

  function log (level, caller, message) {
    var date = new Date()
    var txt = format('{0}-{1}-{2} {3}:{4}:{5}.{6} |-{7} [{8}] {9}',
      date.getFullYear(),
      (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1),
      (date.getDate() < 10 ? '0' : '') + date.getDate(),
      (date.getHours() < 10 ? '0' : '') + date.getHours(),
      (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(),
      (date.getSeconds() < 10 ? '0' : '') + date.getSeconds(),
      (date.getMilliseconds() < 100 ? (date.getMilliseconds() < 10 ? '00' : '0') : '') + date.getMilliseconds(),
      level,
      caller || 'anonymous',
      message
    )
    if (debug || level === 'INFO') {
      console.info(txt)
      consoleArea.append(txt + '\n').scrollTop(consoleArea[0].scrollHeight)
    }
  }

  function format (fmt) {
    var result = fmt
    if (arguments.length > 1) {
      for (var i = 1; i < arguments.length; i++) {
        var reg = new RegExp('\\{' + (i - 1) + '\\}', 'g')
        result = result.replace(reg, (typeof arguments[i] !== 'undefined' && arguments[i] != null) ? arguments[i] : '')
      }
    }
    return result
  }
}(window.jQuery))
